from app import db
from datetime import datetime

class AIConfig(db.Model):
    """AI接口配置表"""
    __tablename__ = 'ai_configs'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, comment='配置名称')
    provider = db.Column(db.String(50), nullable=False, comment='服务提供商: stable_diffusion, baidu, aliyun等')
    
    # API配置
    api_endpoint = db.Column(db.String(500), nullable=False, comment='API端点')
    api_key = db.Column(db.String(500), nullable=False, comment='API密钥')
    api_secret = db.Column(db.String(500), nullable=True, comment='API密钥（如需要）')
    
    # 模型配置
    model_name = db.Column(db.String(100), nullable=False, comment='模型名称')
    model_version = db.Column(db.String(50), nullable=True, comment='模型版本')
    
    # 默认参数
    default_width = db.Column(db.Integer, default=512, comment='默认宽度')
    default_height = db.Column(db.Integer, default=512, comment='默认高度')
    default_steps = db.Column(db.Integer, default=20, comment='默认步数')
    default_cfg_scale = db.Column(db.Float, default=7.0, comment='默认CFG Scale')
    
    # 限制设置
    max_width = db.Column(db.Integer, default=1024, comment='最大宽度')
    max_height = db.Column(db.Integer, default=1024, comment='最大高度')
    max_steps = db.Column(db.Integer, default=50, comment='最大步数')
    
    # 计费设置
    cost_per_request = db.Column(db.Float, default=0.0, comment='每次请求成本')
    monthly_quota = db.Column(db.Integer, default=1000, comment='月配额')
    used_quota = db.Column(db.Integer, default=0, comment='已用配额')
    
    # 状态设置
    is_active = db.Column(db.Boolean, default=True, comment='是否启用')
    is_default = db.Column(db.Boolean, default=False, comment='是否为默认配置')
    priority = db.Column(db.Integer, default=1, comment='优先级，数字越大优先级越高')
    
    # 健康状态
    health_status = db.Column(db.String(20), default='unknown', comment='健康状态: healthy, degraded, down, unknown')
    last_health_check = db.Column(db.DateTime, nullable=True, comment='上次健康检查时间')
    response_time = db.Column(db.Float, nullable=True, comment='平均响应时间(秒)')
    error_rate = db.Column(db.Float, default=0.0, comment='错误率')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    def __repr__(self):
        return f'<AIConfig {self.name}>'
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'provider': self.provider,
            'model_name': self.model_name,
            'model_version': self.model_version,
            'default_width': self.default_width,
            'default_height': self.default_height,
            'default_steps': self.default_steps,
            'default_cfg_scale': self.default_cfg_scale,
            'max_width': self.max_width,
            'max_height': self.max_height,
            'max_steps': self.max_steps,
            'cost_per_request': self.cost_per_request,
            'monthly_quota': self.monthly_quota,
            'used_quota': self.used_quota,
            'is_active': self.is_active,
            'is_default': self.is_default,
            'priority': self.priority,
            'health_status': self.health_status,
            'last_health_check': self.last_health_check.isoformat() if self.last_health_check else None,
            'response_time': self.response_time,
            'error_rate': self.error_rate,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    def update_health_status(self, status, response_time=None):
        """更新健康状态"""
        self.health_status = status
        self.last_health_check = datetime.utcnow()
        if response_time is not None:
            self.response_time = response_time
        db.session.commit()
    
    def increment_usage(self):
        """增加使用次数"""
        self.used_quota += 1
        db.session.commit()
    
    def reset_monthly_quota(self):
        """重置月配额"""
        self.used_quota = 0
        db.session.commit()